package libs

import (
	"errors"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

type curlRequest struct {
}

func NewCurlRequest() *curlRequest {
	return &curlRequest{}
}

// HttpGet 简单get请求
func (c *curlRequest) HttpGet(url string) (content string, err error) {
	resp, err := http.Get(url)

	if err != nil {
		return "", err
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)

	return string(body), nil
}

// HttpPost post请求,不能设置header
func (c *curlRequest) HttpPost(url string, params []byte, contentType string) (content string, err error) {

	if contentType == "" {
		contentType = "application/json"
	}

	resp, err := http.Post(url, contentType, strings.NewReader(string(params)))

	if err != nil {
		return "", err
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)

	return string(body), nil
}

// HttpRequest get/post请求,可设置header
func (c *curlRequest) HttpRequest(url string, method string, data string, header map[string]string) (content string, err error) {
	var req *http.Request
	method = strings.ToUpper(method)
	if method == "POST" {
		req, err = http.NewRequest(method, url, strings.NewReader(data))
		// 表单方式(必须)
		n := len(header)
		if n == 0 {
			header = make(map[string]string, 0)
			header["Content-Type"] = "application/json"
			//AJAX 方式请求
			header["x-requested-with"] = "XMLHttpRequest"
		}

		for k, v := range header {
			req.Header.Add(k, v)
		}

	} else if method == "GET" {
		req, err = http.NewRequest(method, url+"?"+data, nil)
	} else {
		return "", errors.New("the request method does not exist")
	}

	if err != nil {
		return "", err
	}

	client := &http.Client{}

	resp, err := client.Do(req)

	if err != nil {
		return "", err
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	return string(body), nil
}

// URLParams 拼接字符串,官方提供方法(中文友好)
func (c *curlRequest) URLParams(params map[string]string) (query string) {
	var urlQuery url.URL
	q := urlQuery.Query()
	for k, v := range params {
		q.Add(k, v)
	}

	query = q.Encode()
	return
}
